/**
 * 请求，登录模块
 */

/**
 * 域名链接
 */
let api = "https://www.aoc-ppns.cn";

const extractCsrfTokens = function(res) {

	let csrfTokenCookie = res.cookies.find(item => -1 != item.indexOf("csrftoken"));
	if (undefined == csrfTokenCookie) {
		return null;
	}
	csrfTokenCookie = csrfTokenCookie.split(";").filter(item => -1 == item.indexOf("Path=/")).join(";");
	const valAttr = res.data.split(" ").find(item => -1 != item.indexOf('value="'))
	if (undefined == valAttr) {
		return null;
	}
	const csrfmiddlewareToken = valAttr.split('"')[1];
	return {
		csrfTokenCookie,
		csrfmiddlewareToken
	};
};



/**
 * @func reqeust 数据请求接口封装
 * @param {Object} data 接口需要的参数
 * @return {*}  返回请求成功的数据 
 */
const request = async function(datas) {

	let {
		url,
		data,
		method,
		header={}
	} = datas;

	let token = uni.getStorageSync('token'),
		isTrue = '';

	if (token) {
		header = {
			'content-type': header['content-type'] ? header['content-type']:"application/x-www-form-urlencoded",
			'cookie': uni.getStorageSync('cookie'),
			'X-CSRFToken': token
		}
	}

	let newData = '';
	if (data && method) {
		let keys = Object.keys(data);
		keys.forEach(item => {
			(newData != "") && (newData += '&');

			if (typeof data[item] == 'object') {
				newData += `${item}=${encodeURIComponent(JSON.stringify(data[item]))}`
			} else {
				newData += `${item}=${encodeURIComponent(data[item])}`
			}
		})
	} else {
		newData = data
	}


	let [err, res] = await uni.request({
		url: api + url,
		data: newData ? newData : '',
		header: header ? header : {},
		method: method ? method : 'GET',
	})

	console.log(res);

	if (res) {
		switch (res.statusCode) {
			case 200:
				return Promise.resolve(res);
				break;
			case 401:
				uni.hideLoading();
				errLogin("您还没有登录，请登录");
				return false;
				break;
			case 403:
				uni.hideLoading();
				errLogin("登录失败！请重新登录");
				return Promise.reject();
				break;
			case 422:
				uni.hideLoading();
				uni.showToast({
					title: "无效的请求参数。",
					icon: 'none'
				})
				return Promise.reject();
				break;
			default:
				return Promise.reject();
				break;
		}
	} else {
		return Promise.reject()
		uni.hideLoading();
		uni.showModal({
			title: "网络错误",
			content: '网络开了小差，请刷新重试下哦~',
			confirmText: '复制错误',
			success(res) {
				if (res.confirm) {
					uni.setClipboardData({
						data: err.errMsg
					})
				}
			}
		})
	}
}

/**
 * @func login 获取登录凭证code
 * @return {Promise}  
 */

const login = function() {
	return new Promise((resolve, reject) => {
		uni.login({
			success(res) {
				if (res.code) {
					resolve(res.code);
				} else {
					errLogin("登录失败！请重新登录")
				}
			}
		})
	})
}



/**
 * @func getUserProfile 获取用户信息
 * @return {Object}  返回用户信息
 */

const getUserProfile = function() {
	return new Promise((resolve, reject) => {
		uni.getUserProfile({
			desc: "获取用户信息",
			success(res) {
				resolve(res)
			},
			fail() {
				errLogin("登录失败！请重新登录");
			}
		})
	})
}

/**
 * @func errLogin 登录失败或未登录提示重新登录
 * @param {String} msg 提示文字
 */

const errLogin = function(msg) {
	uni.showModal({
		title: "提示",
		content: msg,
		confirmText: '登录',
		success(res) {
			if (res.confirm) {
				// 登录
				getUserInfo()
			} else {
				uni.showToast({
					title: "您取消了登录",
					icon: 'none'
				})
			}
		}
	})
}

/**
 * @func getUserInfo 用户登录
 */
let isClick = true;
const getUserInfo = function() {
	if (isClick) {
		isClick = false;
		Promise.all([login(), getUserProfile()])
			.then(res => {
				uni.showLoading({
					title: "登录中...",
				})
				request({
						url: "/patient/login_wx/",
						method: "POST",
						data: {
							code: res[0],
							userInfo: res[1].userInfo,
							// rawData: res[1].rawData,
							// signature: res[1].signature,
							// encryptedData: res[1].encryptedData,
							// iv: res[1].iv
						}
					})
					.then(result => {
						uni.hideLoading({
							success() {
								let cookies = result.cookies.find(item => item.indexOf(
										'sessionid') != -
									1);
								cookies = cookies.split('; ').find(item => item.indexOf(
										'sessionid') !=
									-1);

								cookies = wx.getStorageSync('cookie') + '; ' + cookies;

								uni.setStorageSync('cookie', cookies);
								wx.setStorageSync('userinfo', res[1].userInfo)
								uni.showToast({
									title: "登录成功",
									icon: 'success'
								})
								getCurrentPages()[getCurrentPages().length - 1].onShow();

								isClick = true;

							}
						})
					})
			}).catch(err => {
				isClick = true;
			})
	}
}

/**
 * @func isLogin 判断用户是否登录，没有登录重新登录
 * @return {Boolean}  false 未登录  true 登录
 */

const isLogin = function() {
	let user = uni.getStorageSync('userinfo');
	if (user) {
		return true
	} else {
		errLogin("您还没有登录，请登录");
		return false
	}

}

/**
 * @func deepClone 深度拷贝
 * @param {*} target 
 * @return {*}
 */

const deepClone = function(target) {
	if (typeof target != 'object') {
		return target;
	}
	let type = Object.prototype.toString.call(target);
	let cloneTarget = type == "[object Array]" ? [] : type == "[object Object]" ? {} : null;
	let keys = type == "[object Array]" ? undefined : Object.keys(target);
	let newTarget = keys || target;
	newTarget.forEach((item, index) => {
		if (keys) {
			index = item;
		}
		cloneTarget[index] = deepClone(target[index])
	})
	return cloneTarget;
}


/**
 * @param {Object} times  时间
 * @param {Object} format 显示方式
 * @return {String}  时间
 */
const getTime = function(times, format) {
	let formats = format.split(''),
		time = '';
	let date = {
		Y: new Date(times).getFullYear(),
		M: new Date(times).getMonth() + 1,
		D: new Date(times).getDate(),
		h: new Date(times).getHours(),
		m: new Date(times).getMinutes(),
		s: new Date(times).getSeconds()
	}
	formats.forEach(item => {
		if (item in date) {
			time += date[item] < 10 ? '0' + date[item] : date[item]
		} else {
			time += item
		}
	})
	return time;
}


export default {
	request,
	api,
	getUserInfo,
	isLogin,
	deepClone,
	extractCsrfTokens,
	getTime
}
